<?php
/**
 * @copyright: ©2024 永州微聚 商网络科技有限公司
 * @link: https://www.weijuYunke.com
 */
namespace app\mobile\controller;

use app\BaseController;
use think\App;
use think\facade\Request;
use think\facade\Db;
use think\facade\Log;
use think\Model;
use app\admin\model\FigurePartner;
use app\admin\model\FigurePartnerSet;
use app\admin\model\SystemUser;
use app\admin\model\FigureUser;
use app\admin\model\FigurePartnerLog;
use app\admin\model\FigureCard;
use app\admin\model\FigureCardGoods;
use app\admin\model\FigureCardLog;

/**
 * 合伙人
 *
 * @author Administrator
 *        
 */
class Partner extends BaseController
{

    /**
     * 合伙人设置
     * http://aigc.weijuyunke.cn/mobile/partner/set
     */
    public function set()
    {
        $request = $this->request;
        $user_id = $this->request->_UID;
        
        $set = FigurePartnerSet::where("id", 1)->find();
        
        if (empty($set)) {
            $set = [];
        }
        
        if (! empty($set['protocol'])) {
            $set['protocol'] = htmlspecialchars_decode($set['protocol']);
        }
        
        return result(0, 'success', $set);
    }

    /**
     * 申请合伙人
     * http://aigc.weijuyunke.cn/mobile/partner/apply
     *
     * @param
     *            uid
     * @param
     *            name 姓名
     * @param
     *            telphone 手机号
     */
    public function apply()
    {
        try {
            $uid = input('uid');
            if (empty($uid)) {
                return result(1, 'uid为空');
            }
            
            $user = FigureUser::where('id', $uid)->find();
            
            if (empty($user)) {
                return result(- 1, '未找到用户');
            }
            
            $partner = FigurePartner::where("uid = {$uid} AND is_status != 3 ")->find();
            
            if ($partner) {
                return result(- 1, '该用户已申请');
            }
            
            $set = FigurePartnerSet::where("id", 1)->find();
            
            if (isset($set) && $set['is_money'] == 1 && $set['money'] > 0) {
                $data = array(
                    'log_no' => getPayNo('PA'),
                    'uid' => $uid,
                    'name' => input('name'),
                    'telphone' => input('telphone'),
                    'money' => $set['money'],
                    'pay_status' => 1,
                    'create_time' => time()
                );
                FigurePartnerLog::insert($data);
                return result(0, '申请成功', $data['log_no']);
            } else {
                
                $data = array(
                    'uid' => $uid,
                    'name' => input('name'),
                    'telphone' => input('telphone'),
                    'is_status' => 1,
                    'create_time' => time()
                );
                
                $id = FigurePartner::insertGetId($data);
                
                if (! empty($id)) {
                    return result(0, '申请成功，待审核');
                } else {
                    return result(- 1, '申请失败');
                }
            }
        } catch (\Exception $e) {
            return result(- 1, '异常' . $e->getMessage());
            exit();
        }
    }

    /**
     * 合伙人改变状态
     * http://aigc.weijuyunke.cn/mobile/partner/updateStatus
     *
     * @param
     *            name 姓名
     * @param
     *            telphone 手机号
     * @param
     *            partner_id 合伙人id
     */
    public function updateStatus()
    {
        try {
            $partner_id = input('partner_id');
            
            $partner = FigurePartner::where('id', $partner_id)->find();
            
            if (empty($partner)) {
                return result(- 1, '合伙人不存在');
            }
            
            if ($partner['is_status'] != 3) {
                return result(- 1, '合伙人状态异常');
            }
            
            $data = [
                'is_status' => 1
            ];
            
            if (! empty(input('name'))) {
                $data['name'] = input('name');
            }
            
            if (! empty(input('telphone'))) {
                $data['telphone'] = input('telphone');
            }
            
            $partner->save($data);
            return result(0, '申请成功，待审核');
        } catch (\Exception $e) {
            return result(- 1, '异常' . $e->getMessage());
            exit();
        }
    }

    /**
     * 合伙人详情
     * http://aigc.weijuyunke.cn/mobile/partner/info
     *
     * @param
     *            partner_id 合伙人id
     */
    public function info()
    {
        $partner_id = input('partner_id');
        
        $partner = FigurePartner::where('id', $partner_id)->find();
        
        if (empty($partner)) {
            return result(- 1, '合伙人不存在');
        }
        
        if ($partner['is_status'] != 2) {
            return result(- 1, '合伙人状态异常');
        }
        
        $user = FigureUser::where('id', $partner['uid'])->find();
        $partner['avatar'] = empty($user['avatar']) ? '' : $user['avatar'];
        
        $where = " partner_id = {$partner_id} ";
        
        $cardAll = FigureCard::where($where)->count();
        $cardUsed = FigureCard::where($where . " AND is_status = 2 ")->count();
        $cardUnused = FigureCard::where($where . " AND is_status = 1 ")->count();
        
        $partner['cardAll'] = $cardAll;
        $partner['cardUsed'] = $cardUsed;
        $partner['cardUnused'] = $cardUnused;
        
        $date = date('Y-m-d', time());
        $yesterday = date('Y-m-d', strtotime('-1 days'));
        $cardUsedT = FigureCard::where($where . "AND is_status = 2 AND DATE_FORMAT(FROM_UNIXTIME(create_time),'%Y-%m-%d') = '{$date}'")->count();
        $cardUsedY = FigureCard::where($where . " AND is_status = 2 AND DATE_FORMAT(FROM_UNIXTIME(create_time),'%Y-%m-%d') = '{$yesterday}' ")->count();
        
        $partner['cardUsedT'] = $cardUsedT;
        $partner['cardUsedY'] = $cardUsedY;
        
        return result(0, '合伙人信息', $partner);
    }

    /**
     * 卡密商品列表
     * https://aigc.weijuyunke.cn/mobile/partner/goodsList
     *
     * @param
     *            page 页码
     * @param
     *            psize 每页条数
     */
    public function goodsList()
    {
        $pindex = max(1, intval(input('page')));
        $psize = empty(input('psize')) ? 10 : intval(input('psize'));
        
        $where = " is_display = 1  and card_type = 1";
        
        $total = FigureCardGoods::where($where)->count();
        
        if ($total) {
            
            $list = FigureCardGoods::where($where)->order("sort", "DESC")
                ->limit(($pindex - 1) * $psize, $psize)
                ->select();
        } else {
            $list = array();
        }
        
        $totalPage = ceil($total / $psize);
        
        return result(0, 'success', array(
            'list' => $list,
            'total' => $total,
            'pindex' => $pindex,
            'psize' => $psize,
            'totalPage' => $totalPage
        ));
    }

    /**
     * 卡密商品详情
     * https://aigc.weijuyunke.cn/mobile/partner/goodsDetail
     *
     * @param
     *            goods_id 商品id
     */
    public function goodsDetail()
    {
        $goods_id = input('goods_id');
        
        $goods = FigureCardGoods::where('id', $goods_id)->find();
        
        if (empty($goods)) {
            return result(- 1, '商品不存在');
        }
        
        $goods['detail'] = htmlspecialchars_decode($goods['detail']);
        
        return result(0, 'success', $goods);
    }

    /**
     * 合伙人购买卡密
     * https://aigc.weijuyunke.cn/mobile/partner/cardBuy
     *
     * @param
     *            uid
     * @param
     *            partner_id 合伙人id
     * @param
     *            goods_id 商品id
     * @param
     *            count 数量
     */
    public function cardBuy()
    {
        Db::startTrans();
        try {
            
            $uid = input('uid');
            $partner_id = input('partner_id');
            $goods_id = input('goods_id');
            $count = input('count');
            
            $partner = FigurePartner::where('id', $partner_id)->find();
            
            if (empty($partner)) {
                return result(- 1, '合伙人不存在');
            }
            
            $goods = FigureCardGoods::where('id', $goods_id)->find();
            
            if (empty($goods)) {
                return result(- 1, '商品不存在');
            }
            
            if ($goods['inventory'] < $count) {
                return result(- 1, '库存不足');
            }
            
            $data = array(
                'uid' => $uid,
                'log_no' => getPayNo('CA'),
                'partner_id' => $partner_id,
                'goods_id' => $goods_id,
                'goods_name' => $goods['name'],
                'goods_pic' => $goods['pic_url'],
                'goods_money' => $goods['money'],
                'goods_quantity' => $goods['quantity'],
                'member_id' => $goods['member_id'],
                'member_name' => $goods['member_name'],
                'goods_day' => $goods['day'],
                'goods_point' => $goods['point'],
                'goods_avatar_twin_count' => $goods['avatar_twin_count'],
                'goods_voice_twin_count' => $goods['voice_twin_count'],
                'goods_second' => $goods['second'],
                'goods_second_infinite' => $goods['second_infinite'],
                'count' => $count,
                'quantity' => $count * $goods['quantity'],
                'money' => $count * $goods['money'],
                'pay_status' => 1
            );
            
            $cardLog = new FigureCardLog();
            $result = $cardLog->save($data);
            
            if (empty($result)) {
                return result(- 1, '下单失败', $data);
            }
            
            Db::commit();
            return result(0, '下单成功', $data['log_no']);
        } catch (\Exception $e) {
            Db::rollback();
            return result(- 1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    /**
     * 卡密购买记录
     * https://aigc.weijuyunke.cn/mobile/partner/cardLogList
     *
     * @param
     *            partner_id 合伙人id
     * @param
     *            log_no 订单编号
     * @param
     *            is_status 1:使用中,2:已完成
     * @param
     *            page 页码
     * @param
     *            psize 每页条数
     */
    public function cardLogList()
    {
        $partner_id = input('partner_id');
        $partner = FigurePartner::where('id', $partner_id)->find();
        
        if (empty($partner)) {
            return result(- 1, '合伙人不存在');
        }
        
        $pindex = max(1, intval(input('page')));
        $psize = empty(input('psize')) ? 10 : intval(input('psize'));
        
        $where = " pay_status = 2 AND partner_id  = {$partner_id} ";
        
        if (! empty(input('log_no'))) {
            $log_no = input('log_no');
            $where .= " AND log_no LIKE '%{$log_no}%'";
        }
        
        if (! empty(input('is_status'))) {
            $is_status = input('is_status');
            $where .= " AND is_status = {$is_status}";
        }
        
        $total = FigureCardLog::where($where)->count();
        
        if ($total) {
            
            $list = FigureCardLog::where($where)->order("create_time", "DESC")
                ->limit(($pindex - 1) * $psize, $psize)
                ->select();
        } else {
            $list = array();
        }
        
        $totalPage = ceil($total / $psize);
        
        return result(0, 'success', array(
            'list' => $list,
            'total' => $total,
            'pindex' => $pindex,
            'psize' => $psize,
            'totalPage' => $totalPage
        ));
    }

    /**
     * 卡密购买记录删除
     * https://aigc.weijuyunke.cn/mobile/partner/cardLogDel
     *
     * @param
     *            partner_id 合伙人id
     * @param
     *            log_id 记录id
     */
    public function cardLogDel()
    {
        Db::startTrans();
        try {
            $log_id = input('log_id');
            $partner_id = input('partner_id');
            
            $partner = FigurePartner::where('id', $partner_id)->find();
            
            if (empty($partner)) {
                return result(- 1, '合伙人不存在');
            }
            
            $log = FigureCardLog::where([
                'partner_id' => $partner_id,
                'id' => $log_id
            ])->find();
            
            if (empty($log)) {
                return result(- 1, '记录不存在');
            }
            
            $log->delete();
            
            Db::table('wjyk_figure_card')->where(" log_id = {$log_id}")->delete();
            
            Db::commit();
            return result(0, '删除成功');
        } catch (\Exception $e) {
            Db::rollback();
            return result(- 1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    /**
     * 卡密列表
     * https://aigc.weijuyunke.cn/mobile/partner/cardList
     *
     * @param
     *            partner_id 合伙人id
     * @param
     *            log_id 记录id
     * @param
     *            nickname 用户昵称
     * @param
     *            is_status 1:未使用,2:已使用
     * @param
     *            page 页码
     * @param
     *            psize 每页条数
     */
    public function cardList()
    {
        try {
            $log_id = input('log_id');
            $partner_id = input('partner_id');
            
            $partner = FigurePartner::where('id', $partner_id)->find();
            
            if (empty($partner)) {
                return result(- 1, '合伙人不存在');
            }
            
            $log = FigureCardLog::where([
                'partner_id' => $partner_id,
                'id' => $log_id
            ])->find();
            
            if (empty($log)) {
                return result(- 1, '记录不存在');
            }
            
            $pindex = max(1, intval(input('page')));
            $psize = empty(input('psize')) ? 10 : intval(input('psize'));
            
            $where = " a.partner_id  = {$partner_id} AND a.log_id  = {$log_id} ";
            
            if (! empty(input('nickname'))) {
                $nickname = input('nickname');
                $where .= " AND b.nickname LIKE '%{$nickname}%'";
            }
            
            if (! empty(input('is_status'))) {
                $is_status = input('is_status');
                $where .= " AND a.is_status = {$is_status}";
            }
            
            $total = FigureCard::alias('a')->leftJoin('wjyk_figure_user b', 'a.uid=b.id')
                ->where($where)
                ->count();
            
            if ($total) {
                $list = FigureCard::alias('a')->leftJoin('wjyk_figure_user b', 'a.uid=b.id')
                    ->where($where)
                    ->field("a.*,b.avatar,b.nickname")
                    ->order("a.id", "DESC")
                    ->limit(($pindex - 1) * $psize, $psize)
                    ->select();
            } else {
                $list = array();
            }
            
            $totalPage = ceil($total / $psize);
            
            return result(0, 'success', array(
                'list' => $list,
                'total' => $total,
                'pindex' => $pindex,
                'psize' => $psize,
                'totalPage' => $totalPage
            ));
        } catch (\Exception $e) {
            return result(- 1, '异常' . $e->getLine() . "--->" . $e->getMessage());
            exit();
        }
    }

    public static function update_partner($log_no, $price)
    {
        try {
            
            $log = FigurePartnerLog::where('log_no', $log_no)->find();
            
            if ($log['pay_status'] == 2) {
                exit();
            }
            
            $log['money'] = (float) $log['money'];
            $price = (float) $price;
            
            if (bccomp($log['money'], $price, 2) != 0) {
                Log::error("Partner update_partner  交易异常   记录金额" . $log['money'] . "  支付金额" . $price);
                exit();
            }
            
            FigurePartnerLog::where('log_no', $log_no)->update([
                'pay_status' => 2
            ]);
            
            $uid = $log['uid'];
            
            $partner = FigurePartner::where("uid", $uid)->find();
            if (empty($partner)) {
                
                $figurePartner = new FigurePartner();
                $figurePartner->save([
                    'uid' => $uid,
                    'name' => $log['name'],
                    'telphone' => $log['telphone'],
                    'is_status' => 1
                ]);
            }
        } catch (\Exception $e) {
            Log::error("Partner update_partner 失败   error:" . $e->getLine() . '--->' . $e->getMessage());
        }
    }
}